package com.bwc.common;


import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器,会被springBoot自动扫描
 */
@RestControllerAdvice
//@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 处理数据库表中 不能唯一字段重复的异常 如果处理的异常是SQLIntegrityConstraintViolationException，但是
     * @param ex
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.info(ex.getMessage());

        if(ex.getMessage().contains("Duplicate entry")){
            String[] split = ex.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return R.error(msg);
        }

        return R.error("未知错误");
    }

    /**
     * 处理业务异常
     * @param bussinessException
     * @return
     */
    @ExceptionHandler(BussinessException.class)
    public R<String> doBusinessException(BussinessException bussinessException){
//        log.info("{}",bussinessException.getMessage());
        return R.error(bussinessException.getMessage());
    }


    //不属于上面两种的未知异常
    @ExceptionHandler(Exception.class)
    public R<String> doOtherException(Exception ex){
        return R.error("系统繁忙，请稍后再试！");
    }


}
